package com.lqk.demo.pessimisticlock.reentrantLock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author lqk
 * @date 2021/12/23 14:12
 */
public class ReentrantLock4 {
    /**
     * 公平锁
     * 公平锁一般没有必要，会降低并发度，后面分析原理时会讲解
     * @param args
     */
    public static void main(String[] args) {
        ReentrantLock lock = new ReentrantLock(true);
        lock.lock();
        for (int i = 0; i < 500; i++) {
            new Thread(() -> {
                lock.lock();
                try {
                    System.out.println(Thread.currentThread().getName() + " running...");
                } finally {
                    lock.unlock();
                }
            }, "t" + i).start();
        }
        // 1s 之后去争抢锁
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        new Thread(() -> {
            System.out.println(Thread.currentThread().getName() + " start...");
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + " running...");
            } finally {
                lock.unlock();
            }
        }, "强行插入").start();
        lock.unlock();
    }
}
